//
//  PreferencesView.m
//  MobileZIPCodes
//
//  Created by Andreas Schwelling on 02.12.07.
//	http://www.andi.de/zipcodes/
// 
//  Released under the GNU General Public License.
//  See LICENSE for details.
//
//  Use at your own risk.
//
#import "PreferencesView.h"


@implementation PreferencesTable 


- (void)setInstalledCountries:(NSMutableArray*)ic {
	_installedCountries = ic;
}

- (void)setAvailableCountries:(NSMutableArray*)ac {
	_availableCountries = ac;
}

#pragma mark - delegated methods -

- (BOOL)canDeleteRow:( int)row {
	//NSLog(@"canDeleteRow: %d",row);
	int _installedCountriesNumber = [_installedCountries count];
	if (row >= 7 && row<_installedCountriesNumber+7) return YES; else return NO;
}

- (BOOL)canInsertAtRow:(int)row {
	int _availableCountriesNumber = [_availableCountries count];
	if (row >= (10+[_installedCountries count]) && row<_availableCountriesNumber+(10+[_installedCountries count])) return YES; else return NO;
}



- (BOOL)canSelectRow:(int)row {
	return NO;
}

- (void)deleteRows:(id)fp8 viaEdge:(int)fp12 {
	//NSLog(@"deleteRows: %@ viaEdge: %d",fp8,fp12);
}



/*- (void)insertItems:(id)fp8 deleteItems:(id)fp12 andReloadIndexes:(id)fp16 {
 NSLog(@"insertItems: %@ deleteItems: %@ andReloadIndexes %@",fp8,fp12,fp16);
 [super insertItems:fp8 deleteItems:fp12 andReloadIndexes:fp16 ];
 }*/




@end



@implementation PreferencesView

- (id)initWithFrame:(struct CGRect)rect {
	
	self = [super initWithFrame:rect];
	_self = self;
	_rect = rect;
	_navBar  = [[UINavigationBar alloc] init];
	[_navBar setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 48.0f)];
	[_navBar setDelegate:self];
	[_navBar enableAnimation];
	
	[_navBar pushNavigationItem: [[UINavigationItem alloc] initWithTitle: @"Preferences"]];	
	
	[self addSubview:_navBar];
	
	_table = [[PreferencesTable alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y+48.0f, rect.size.width, rect.size.height-49.0f-48.0f)];
	[_table setDataSource:self];
	[_table setDelegate:self];
	
	
	
	_installedCountries = [[_dm getInstalledCountries] retain];
	if (_installedCountries == nil) _installedCountries = [[NSMutableArray alloc] init];
	_localAvailableCountries = [_dm getLocalAvailableCountries];
	
	if ([_delegate getPerformUpdate]) {
		
		[_dm loadRemotePList];
		_remoteAvailableCountries = [[_dm getRemoteAvailableCountries] retain];	
		if (_remoteAvailableCountries != nil) 		[_dm setPListParam:[_dm getRemoteData] key:@"availablecountries"];
	}	
	
	_newAvailableCountries = [_remoteAvailableCountries count] - [_localAvailableCountries count];
	_localAvailableCountries = [[_dm getLocalAvailableCountries] retain];

	//NSLog(@"local known c: %d",[_localAvailableCountries count]);
	//NSLog(@"remote known c: %d",[_remoteAvailableCountries count]);
	if (_newAvailableCountries<0) _newAvailableCountries = 0;
	
	int i=0;
	for (i=0;i<[_installedCountries count];i++) {
		
		
		[_localAvailableCountries removeObject:[_installedCountries objectAtIndex:i]];
	}
	
	
	[_installedCountries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
	[_localAvailableCountries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
	
	NSMutableDictionary* cellDict = [[NSMutableDictionary alloc] initWithCapacity:[_localAvailableCountries count]];
	
	
	
	
	_hasChanged = NO;
	
	[_table reloadData];
	[_table setInstalledCountries:_installedCountries];
	[_table setAvailableCountries:_localAvailableCountries];
	[_table enableRowDeletion:YES animated:YES];
	
	[self addSubview:_table];
	
	
	
	
	return self;
	
}

-(void)dealloc {
	[_navBar release];
	
	[super dealloc];
	
}

- (BOOL) getHasChanged {
	return _hasChanged;
}


- (void) processChanges {
	
	
	
	
	
	DataManager *dm = [DataManager alloc];
	NSMutableArray *originalInstalled = [dm getInstalledCountries];
	
	NSMutableArray *newInstalled = [[NSMutableArray alloc] init];
	[newInstalled addObjectsFromArray:_installedCountries];
	
	int i=0;
	for (i=0;i<[originalInstalled count];i++) {
		[newInstalled removeObject:[originalInstalled objectAtIndex:i]];
	}
	
	//NSLog(@"countries to be installed: %@",newInstalled);
	
	
	_downloadCountries = [[NSMutableArray alloc] init];
	[_downloadCountries addObjectsFromArray:newInstalled];	
	[newInstalled release];

	[_newToInstallCountries release];
	_newToInstallCountries = [[NSMutableArray alloc] init];
	_newToInstallCountries = [_downloadCountries copy];
	
	newInstalled = [[NSMutableArray alloc] init];
	[newInstalled addObjectsFromArray:_installedCountries];
	
	for (i=0;i<[newInstalled count];i++) {
		[originalInstalled removeObject:[newInstalled objectAtIndex:i]];
	}	
	
	//NSLog(@"countries to be removed: %@",originalInstalled);
	
	_removeCountries = [originalInstalled copy];
	
	if ([_downloadCountries count] > 0 || [_removeCountries count] > 0) {
		
		UIAlertSheet *_nodatasheet = [ [ UIAlertSheet alloc ] initWithFrame:
									  CGRectMake(0, 240, 320, 240) ];
		[ _nodatasheet setTitle:@"Apply changes" ];
		[ _nodatasheet setBodyText:@"Do you really want to save your changes (files will be downloaded over EDGE or WiFi if necessary)?"];
		[ _nodatasheet addButtonWithTitle:@"OK" ];
		[ _nodatasheet addButtonWithTitle:@"Cancel" ];
		[_nodatasheet setAlertSheetStyle:1];
		[ _nodatasheet setDelegate: self ];
		[ _nodatasheet setRunsModal:YES];
		[_nodatasheet presentSheetInView:self];
		
	}
	
	//NSLog(@"afterward");
	
	[dm release];
	
	
	
}

- (void) downloadFailed {
	
	if (_downloadFailed == NO) {
		[_downloadCountries insertObject:_actualDownload atIndex:0];
		_downloadFailed = YES;
		[self downloadNextFile:nil];
		//NSLog(@"downloadfailed was NO, now YES");
		return;
	}
	
	
	DataManager *dm = [DataManager alloc];
	
	[_installedCountries removeObjectsInArray:_newToInstallCountries];
	
	[dm setInstalledCountries:_installedCountries];

	[dm release];

	[_downloadSheet dismiss];
	[_downloadSheet release];
	
	_downloadSuccessSheet = [ [ UIAlertSheet alloc ] initWithFrame:
							 CGRectMake(0, 240, 320, 240) ];
	[ _downloadSuccessSheet setTitle:@"Error!" ];
	[ _downloadSuccessSheet setBodyText:@"Download failed! Please try again later!\n" ];
	[_downloadSuccessSheet setAlertSheetStyle:1	];
	[ _downloadSuccessSheet presentSheetInView: _delegate ];
	[_delegate reloadBrowseAndSearch];
	[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(dismissDownloadSheet:) userInfo:nil repeats:NO];

	
	/*
	_downloadFailed = NO;
	[self downloadNextFile:nil];
	 */
	//NSLog(@"downloadfailed  NO, next one");
	return;
}


- (void) setUpgradeProgress:(int)byte {
	
	_downloaded += byte;
	_filedownloaded += byte;
	//NSLog(@"progress percent: %f - got %d, total %d",(float)_downloaded/_totaldownloadsize,_downloaded,_totaldownloadsize);
	[_progressIndicator setProgress:(float)_downloaded/_totaldownloadsize];
	
	float kbsize = (float)(_filedownloaded/1024);
	float mbsize = kbsize/1024;
	
	
	
	NSString *filesizestr,*downloadsizestr;
	
	if (kbsize>1023) {
		filesizestr = [NSString stringWithFormat:@"%.2f MB",mbsize];
	} else {
		filesizestr = [NSString stringWithFormat:@"%.1f kB",kbsize];
	}
	
	
	kbsize = (float)(_downloadsize/1024);
	mbsize = kbsize/1024;
	
	if (kbsize>1023) {
		downloadsizestr = [NSString stringWithFormat:@"%.2f MB",mbsize];
	} else {
		downloadsizestr = [NSString stringWithFormat:@"%.1f kB",kbsize];
	}
	
	//NSLog(@"downloadsizestr %@",downloadsizestr);
	
	
	[ _downloadSheet setBodyText:[NSString stringWithFormat:@"%@ (%@ of %@)\n\n",_actualDownload,filesizestr,downloadsizestr] ];
	
	
	
	
}

- (void) downloadFinished {
	
	_downloadFailed = NO;
	[self downloadNextFile:nil];
	
}

- (void) dismissDownloadSheet:(id)p {
	
	[_downloadSuccessSheet dismiss];
	[_downloadSuccessSheet release];
	
	
}

- (void) downloadNextFile:(id)p {
	
	if ([_downloadCountries count] ==0) {
		[_downloadSheet dismiss];
		[_downloadSheet release];
		
		_downloadSuccessSheet = [ [ UIAlertSheet alloc ] initWithFrame:
								 CGRectMake(0, 240, 320, 240) ];
		[ _downloadSuccessSheet setTitle:@"Downloading..." ];
		[ _downloadSuccessSheet setBodyText:@"Downloads finished!\n" ];
		[_downloadSuccessSheet setAlertSheetStyle:1	];
		[ _downloadSuccessSheet presentSheetInView: _delegate ];
		
		[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(dismissDownloadSheet:) userInfo:nil repeats:NO];
		
		
		return;
		
	}
	
	
	DataManager *dm = [DataManager alloc];
	
	NSString *nextfile = [_downloadCountries objectAtIndex:0];
	_actualDownload = [nextfile copy];
	[_downloadCountries removeObjectAtIndex:0];
	//NSLog(@"next one: %@",nextfile);
	
	NSString *url;
	if (_downloadFailed == NO)
		url = [dm getRemoteFilesource:nextfile];
	else
		url = [dm getRemoteFileMirror:nextfile];
	
	
	
	//NSLog(@"url: %@",url);
	
	
	
	NSString *filename = [NSMutableString stringWithString:nextfile];
	[filename replaceOccurrencesOfString:@" " withString:@"" options:NULL range:NSMakeRange(0, [filename length])];		
	filename = [[filename lowercaseString] stringByAppendingString:@".dat"];
	filename = [@"/var/root/Media/ZIPcodes/" stringByAppendingString:filename];
	
	_downloadsize = [[dm getFileSizeForCountry:nextfile] intValue];
	
	float kbsize = (float)(_downloadsize/1024);
	float mbsize = kbsize/1024;
	
	
	NSString *filesizestr;
	
	if (kbsize>1023) {
		filesizestr = [NSString stringWithFormat:@"%.2f MB",mbsize];
	} else {
		filesizestr = [NSString stringWithFormat:@"%.1f kB",kbsize];
	}
	
	
	[ _downloadSheet setBodyText:[NSString stringWithFormat:@"%@... (%.1f of %@)\n\n",_actualDownload,0.0,filesizestr] ];
	
	[_downloader release];
	_filedownloaded = 0;
	_downloader = [Downloader downloadURL: url to: filename delegate: self];
	
}


- (void) downloadAndDelete {
	
	if ([_removeCountries count]>0) {
		
		DataManager *dm = [DataManager alloc];
		int i=0;
		for (i=0;i<[_removeCountries count];i++) {
			
			[dm deleteDatabaseFile:[_removeCountries objectAtIndex:i]];			
		}		
		[dm release];
		
	}
	
	if ([_downloadCountries count]>0) {
		_downloadSheet = [ [ UIAlertSheet alloc ] initWithFrame:
						  CGRectMake(0, 240, 320, 240) ];
		[ _downloadSheet setTitle:@"Downloading..." ];
		[ _downloadSheet setBodyText:@"Downloading\n\n" ];
		//[ updateSheet addButtonWithTitle:@"Cancel" ];
		// [ updateSheet addButtonWithTitle:@"OK" ];
		[ _downloadSheet setDelegate: self ];
		[_downloadSheet setAlertSheetStyle:1	];
		_progressIndicator = [[UIProgressBar alloc] initWithFrame:CGRectMake(60.0f, 55.0f, 200.0f,50.0f)];
		[_downloadSheet addSubview:_progressIndicator];
		[ _downloadSheet presentSheetInView: _delegate ];
		
		DataManager *dm = [DataManager alloc];
		_downloadFailed = NO;
		_totaldownloadsize = 0;
		int i=0;
		for (i=0;i<[_downloadCountries count];i++) {
			
			int size = [[dm getFileSizeForCountry:[_downloadCountries objectAtIndex:i]] intValue];
			_totaldownloadsize += size;
			
		}
		
		//NSLog(@"total download size: %d", _totaldownloadsize);
		_downloaded = 0;
		[self downloadNextFile:nil];
		
		[dm release];
	}
	
}



- (int) getnewAvailableCountries {
	//NSLog(@"newavail: %d",_newAvailableCountries);
	return _newAvailableCountries;
}

-(void)setDelegate:(id)del {
	//NSLog(@"delegate: %@",del);
	_delegate = del;
}


- (void) setDataManager:(DataManager*)dm {
	//NSLog(@"setting datamanager %@",dm);
	_dm = dm;
}


#pragma mark - delegated methods -


- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
	
	[sheet dismiss];
	
	//NSLog(@"button: %d",button);
	
	if (button == 1) {
		DataManager *dm = [DataManager alloc];
		[dm setInstalledCountries:_installedCountries];
		[dm release];
		_hasChanged = NO;
		[_navBar showLeftButton:nil withStyle:0 rightButton:nil withStyle:0];
		
		
		[self downloadAndDelete];
		
		
	}
	
	
	
}

- (void)navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
	[self processChanges];
	[_delegate reloadBrowseAndSearch];
}


- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table
{
	return 6;
}


- (float)preferencesTable:(UIPreferencesTable *)table 
			 heightForRow:(int)row 
				  inGroup:(int)group 
	   withProposedHeight:(float)proposed 
{
	//NSLog(@"row: %d, group: %d",row,group);
	
	if ([_installedCountries count]<1 && group ==2) return 0;
	
	if (group == 0 && row == -1) return 10;
	if (group == 0 && row == 0) return 25;
	if (group == 1 && row == -1) return 10;
	
	if (group == 2 && row == -1) return 10;
	if (group == 2 && row == 0) return 25;
	if (group == 3 && row == -1) return 10;
	
	if (group == 4 && row == -1) return 10;
	if (group == 4 && row == 0) return 25;
	if (group == 5 && row == -1) return 10;
	
	
	if (group == 0 || group == 2) {
        return 20;
    }
	
	
    return proposed;
}


- (int)preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group
{
	switch (group)
  {
	  case 0: return 1;
	  case 1: return 1;
	  case 2: return 1;
	  case 3: return [_installedCountries count];
	  case 4: return 1;
	  case 5: return [_localAvailableCountries count];
		  
  }
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForGroup:(int)group
{
	UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
	
	return [cell autorelease];
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group
{
	
	if (group == 0)
	  {
		  
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:@"Update"];
		  [ cell setDrawsBackground: NO ];
		  [cell _setDrawAsGroupTitle:YES];
		  return [cell autorelease];
	  }				
	else if (group == 1)
	  {
		  
		  
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  [cell setTitle:@"Search for updates"];
		  //[cell setAlignment:2];
		  UISwitchControl *autoupdateswitch =  [[ UISwitchControl alloc ] 
												initWithFrame:CGRectMake(200.0f, 8.0f, 120.0f, 30.0f)];
		  [ autoupdateswitch setValue: YES ];
		  [ cell  addSubview:autoupdateswitch ];
		  return [cell autorelease];
		  
		  
		  
	  } 
	else if (group == 2)
	  {
		  
		  
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  if ([_installedCountries count]>0) [cell setTitle:@"Installed Countries"];
		  [ cell setDrawsBackground: NO ];
		  [cell _setDrawAsGroupTitle:YES];
		  return [cell autorelease];
		  
		  
		  
	  } 
	else if (group == 3) 
	  {
		  UIPreferencesTableCell *statecell = [[UIPreferencesTableCell alloc] init];
		  [statecell setTitle:[_installedCountries objectAtIndex:row]];
		  
		  
		  return [statecell autorelease];
	  }
	
	else if (group == 4) 
	  {
		  UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
		  if ([_localAvailableCountries count]>0) [cell setTitle:@"Available Countries"];
		  [ cell setDrawsBackground: NO ];
		  [cell _setDrawAsGroupTitle:YES];
		  
		  return [cell autorelease];
		  
	  }	
	else if (group == 5) 
	  {
		  UIPreferencesTableCell *statecell = [[UIPreferencesTableCell alloc] init];
		  [statecell setTitle:[_localAvailableCountries objectAtIndex:row]];
		  
		  
		  DataManager *dm = [DataManager alloc];
		  
		  UIRightTextLabel *filesizelable = [[UIRightTextLabel alloc] initWithFrame:CGRectMake(290.0f, 16.0f, 200.0f, 15.0f)];
		  
		  int filesize = [[dm getFileSizeForCountry:[_localAvailableCountries objectAtIndex:row]] intValue];
		  
		  float kbsize = (float)(filesize/1024);
		  float mbsize = kbsize/1024;
		  
		  NSString *filesizestr;
		  
		  if (kbsize>1023) {
			  filesizestr = [NSString stringWithFormat:@"%.2f MB",mbsize];
		  } else {
			  filesizestr = [NSString stringWithFormat:@"%.1f kB",kbsize];
		  }
		  
		  
		  [filesizelable setText: filesizestr];
		  
		  
		  struct __GSFont* font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:13];
		  float transparent[4] = {0, 0, 0, 0};
		  [filesizelable setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), transparent)];
		  [filesizelable setWrapsText:YES];
		  [filesizelable setFont:font];
		  [filesizelable realignText];
		  [statecell addSubview:filesizelable];
		  [filesizelable release];
		  [dm release];
		  
		  
		  
		  return [statecell autorelease];
	  }
	
}

- (BOOL)preferencesTable:(UIPreferencesTable *)aTable isLabelGroup:(int)group {
	return NO;
}


- (void)tableRowSelected:(NSNotification *)notification
{
	
	
	
	
}




- (void)table:(UITable*)table deleteRow:(int)row {
	// the remove code
	//[activesArray removeObject:[NSString stringWithFormat:@"%d",row]];
	//NSLog(@" detelet: %d",row);
	//NSLog(@"delete item: %@",[_installedCountries objectAtIndex:row-7]);
	[_localAvailableCountries addObject:[_installedCountries objectAtIndex:row-7]];
	[_installedCountries removeObjectAtIndex:row-7];
	
	[_installedCountries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
	[_localAvailableCountries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
	
	[_navBar showLeftButton:nil withStyle:0 rightButton:@"Save" withStyle:1];
	
	_hasChanged = YES;
	
	[_table reloadData];
}


- (void) table:(UITable *) table insertAtRow:(int) row 
{
    int _installedCountriesCount = [_installedCountries count];
	//NSLog(@" insertrow: %d",row);
	//NSLog(@"insert item: %@",[_localAvailableCountries objectAtIndex:row-(10+_installedCountriesCount)]);
	[_installedCountries addObject:[_localAvailableCountries objectAtIndex:row-(10+_installedCountriesCount)]];
	[_localAvailableCountries removeObjectAtIndex:row-(10+_installedCountriesCount)];
	
	[_installedCountries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
	[_localAvailableCountries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
	
	[_navBar showLeftButton:nil withStyle:0 rightButton:@"Save" withStyle:1];
	
	_hasChanged = YES;
	
	[_table reloadData];
	
    
}





@end
